﻿using BeetleX.XRPC;
using BeetleX.XRPC.Clients;
using EventNext;
using System;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Test;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            StartServer();
            for (int i = 0; i < 100; i++)
            {
                StartSignin(i);
            }
            for (int i = 0; i < 100; i++)
            {
                StartXRpcClient();
            }
            do
            {
                Thread.Sleep(100);
            }
            while (Console.ReadLine() != "exit");
        }

        private static void StartSignin(int i)
        {
            XRPCClient client = new XRPCClient("localhost", 9999);
            client.NetError = new BeetleX.Clients.EventClientError((client, e) =>
            {
                if (e.Error != null)
                    Console.WriteLine(e.Error.Message);
                if (!string.IsNullOrEmpty(e.Message))
                    Console.WriteLine(e.Message);
            });
            client.Connect();
            string tokenId = (i%10).ToString();
            IChatService service = client.Create<IChatService>(tokenId);
            Task<string> content = service.SignIn(i.ToString());
            Console.WriteLine(content.Result);
        }

        static int id = 0;
        private async static void StartXRpcClient()
        {
            int myId = ++id;
            string tokenId = (myId % 10).ToString();
            XRPCClient client = new XRPCClient("localhost", 9999);
            client.NetError = new BeetleX.Clients.EventClientError((client, e) =>
            {
                if(e.Error!=null)
                Console.WriteLine(e.Error.Message);
                if (!string.IsNullOrEmpty(e.Message))
                    Console.WriteLine(e.Message);
            });
            client.Connect();
            IChatService service = client.Create<IChatService>(tokenId);
            ((IHeader)service).Header["token"] = tokenId;
            string textId = Guid.NewGuid().ToString();
            //{
            //    string content = await service.Query(textId, 3);
            //    Console.WriteLine(content);
            //}
            {
                string content = await service.Delay( 1);
                Console.WriteLine(content);
            }
        }

        private static void StartServer()
        {
            XRPCServer server = new XRPCServer();
            server.RPCOptions.LogToConsole = true;
            server.RPCOptions.LogToFile = false;
            server.ServerOptions.DefaultListen.Port = 9999;
            server.ServerOptions.ExecutionContextEnabled = true;
            server.ServerOptions.Encoding = Encoding.UTF8;
            server.Register(Assembly.GetExecutingAssembly());
            server.Open();
            Console.WriteLine("Server started!");
        }
    }
}
